<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="所属公司名" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:goods:add']"
        >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:goods:edit']"
        >修改</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column
        label="所属公司名"
        align="center"
        prop="companyName"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column
        label="联系人"
        align="center"
        prop="contactUser"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column
        label="联系电话"
        align="center"
        prop="contactUserMobile"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column
        label="创建人"
        align="center"
        prop="createBy"
        width="120"
        show-overflow-tooltip
      />

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="120"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="单价"
        align="center"
        prop="goodsPrice"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column
        label="到货时间"
        align="center"
        prop="arriveTime"
        width="180"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-if="scope.row.goodsType === 2">{{ scope.row.arriveTime || '-' }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column
        label="信息过期时间"
        align="center"
        prop="expireTime"
        width="180"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-if="scope.row.goodsType === 1">{{ scope.row.expireTime || '-' }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>




      <el-table-column
        label="交付地点"
        align="center"
        prop="goodsAddress"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column
        label="销售数量"
        align="center"
        prop="goodsNumber"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column
        label="货源性质"
        align="center"
        prop="goodsType"
        width="100"
        :formatter="formatGoodsType"
      />


      <el-table-column
        label="信息大图"
        align="center"
        prop="infoPicUrl"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview
            v-if="scope.row.infoPicUrl"
            :src="scope.row.infoPicUrl"
            :width="50"
            :height="50"
          />
          <span v-else>无</span>
        </template>
      </el-table-column>

      <el-table-column
        label="删除标识"
        align="center"
        prop="isDelete"
        width="120px"
      >
        <template #default="{ row }">
          <span v-if="row.isDelete === 0">正常</span>
          <span v-else-if="row.isDelete === 1">删除</span>
        </template>
      </el-table-column>

      <el-table-column
        label="品牌"
        align="center"
        prop="brandName"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column
        label="型号"
        align="center"
        prop="modelName"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column
        label="配置参数"
        align="center"
        prop="paramDesc"
        width="180"
        show-overflow-tooltip
      />


      <el-table-column
        label="推荐状态"
        align="center"
        prop="recommendStatus"
        width="120px"
      >
        <template #default="{ row }">
          <el-switch
            :value="row.recommendStatus"
            :active-value="1"
            :inactive-value="0"
            @change="updateStatusGoods(row)"
          ></el-switch>
          <span>{{ row.recommendStatus ? "" : "" }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        width="180"
        show-overflow-tooltip
      />

      <el-table-column
        label="状态"
        align="center"
        prop="status"
        width="120px"
      >
        <template #default="{ row }">
          <span v-if="row.status === -1">未审核</span>
          <span v-else-if="row.status === -2">已驳回</span>
          <template v-else>
            <el-switch
              :value="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="toggleStatus(row)"
            ></el-switch>
            <span>{{ row.status ? "上架" : "下架" }}</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column
        label="更新人"
        align="center"
        prop="updateBy"
        width="120"
        show-overflow-tooltip
      />

      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="120"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改基本信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="40vw"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="品牌" prop="brandName">
          <el-input v-model="form.brandName" placeholder="请输入品牌" />
        </el-form-item>

        <el-form-item label="型号" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入型号" />
        </el-form-item>

        <el-form-item label="货源性质" prop="goodsType">
          <el-radio-group v-model="form.goodsType">
            <el-radio :label="1">现货</el-radio>
            <el-radio :label="2">期货</el-radio>
          </el-radio-group>
        </el-form-item>




        <el-form-item label="信息大图" prop="infoPicUrl">
          <minio-image-upload
            v-model="form.infoPicUrl"
            :limit="1"
            :fileSize="50"
            accept="image/*,video/*"
            :fileType="['png', 'jpg', 'jpeg', 'mp4', 'avi']"
            :extraTips="form.infoType === 1 ? '轮播图尺寸： 1920 * 620' : ''"
          />
        </el-form-item>

        <el-form-item label="销售数量" prop="goodsNumber">
          <el-input
            v-model="form.goodsNumber"
            placeholder="请输入销售数量"
            type="number"
          />
        </el-form-item>

        <el-form-item label="单价" prop="goodsPrice">
          <el-input
            v-model="form.goodsPrice"
            placeholder="请输入单价"
            type="number"
          />
        </el-form-item>

        <template v-if="form.goodsType === 1">
          <el-form-item label="信息过期时间" prop="expireTime">
            <el-date-picker
              v-model="form.expireTime"
              type="datetime"
              placeholder="请选择信息过期时间"
              format="yyyy-MM-dd HH:mm:ss"
              :value-format="'yyyy-MM-dd HH:mm:ss'"
            ></el-date-picker>
          </el-form-item>
        </template>

        <template v-if="form.goodsType === 2">
          <el-form-item label="到货时间" prop="arriveTime">
            <el-date-picker
              v-model="form.arriveTime"
              type="datetime"
              placeholder="请选择到货时间"
              format="yyyy-MM-dd HH:mm:ss"
              :value-format="'yyyy-MM-dd HH:mm:ss'"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="批次量/次" prop="batchNum">
            <el-input
              v-model="form.batchNum"
              placeholder="请输入每次交货的批次量"
              :maxlength="11"
              type="number"
            ></el-input>
          </el-form-item>
        </template>


        <el-form-item label="配置参数" prop="paramDesc">
          <el-input
            type="textarea"
            v-model="form.paramDesc"
            placeholder="请输入配置参数"
            rows="3"
          />
        </el-form-item>



        <el-form-item label="联系人" prop="contactUser">
          <el-input v-model="form.contactUser" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactUserMobile">
          <el-input v-model="form.contactUserMobile" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="交付地点" prop="goodsAddress">
          <el-input v-model="form.goodsAddress" placeholder="请输入交付地点" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  addGoods,
  updateGoods,
  toggleGoods,
  updateStatusGoods,
} from "@/api/info/hardware";

import FileUpload from "@/components/FileUpload/shardUpload.vue";

export default {
  name: "Goods",
  dicts: ["info_type"],
  components: { FileUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 基本信息表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null, // Changed from infoTitle to companyName
        infoType: null,
        noticeUserStatus: 0,
        status: null,
      },
      // 表单参数
      form: {
        id: null,
        companyId: null,
        createBy: null,
        createTime: null,
        createUserId: null,
        isDelete: null,
        remark: null,
        updateBy: null,
        updateTime: null,
        updateUserId: null,
        infoDetailDesc: null,
        infoFrom: 1,
        infoPicUrl: null,
        infoSimpleDesc: null,
        infoTitle: null,
        infoType: null,
        nodeId: null,
        noticeUserStatus: 0,
        openUrl: null,
        dictType: null,
        status: null,
        batchNum: "",
        goodsPrice: "",
        arriveTime: "",
        expireTime: "",
      },
      // 表单校验
      rules: {
        batchNum: [
          { required: false }, // Optional field
          { pattern: /^[0-9]*$/, message: "批次量只能输入数字" }
        ],
        contactUser: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
        ],
        infoPicUrl: [
          { required: true, message: '请上传信息大图', trigger: 'blur' },
        ],
        modelName	: [
          { required: true, message: '请输入硬件型号', trigger: 'blur' },
        ],
        contactUserMobile: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^[0-9]*$/, message: '请输入正确的联系电话', trigger: 'blur' }
        ],
        goodsNumber: [
          { required: true, message: '请输入销售数量', trigger: 'blur' },
          { pattern: /^[0-9]*$/, message: '销售数量只能输入数字', trigger: 'blur' }
        ],
        goodsPrice: [
          { required: true, message: '请输入单价', trigger: 'blur' },
          { pattern: /^[0-9]*\.?[0-9]*$/, message: '价格只能输入数字', trigger: 'blur' }
        ]

      },
      currRow: {},
      detailVisible: false,
      isAdd: false,
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    window.addEventListener("beforeunload", this.unloadFunc);
  },
  beforeDestroy() {
    window.removeEventListener("beforeunload", this.unloadFunc);
  },
  methods: {
    formatGoodsType(row, column, cellValue, index) {
      switch (cellValue) {
        case 1:
          return '现货';
        case 2:
          return '期货';
        default:
          return '未知';
      }
    },
    unloadFunc() {
      if (this.open && this.isAdd) {
        localStorage.setItem("goods_add", JSON.stringify(this.form));
      }
    },
    async toggleStatus(row) {
      const { id, status } = row;
      const { code } = await toggleGoods({
        id,
        status: Number(!status),
      });
      if (code === 200) {
        this.$message.success(status ? "下架成功" : "上架成功");
        this.$set(row, "status", Number(!status));
      }
    },

    async updateStatusGoods(row) {
      const { id, recommendStatus } = row;
      const { code } = await updateStatusGoods({
        id,
        status: Number(!recommendStatus),
      });
      if (code === 200) {
        this.$message.success(recommendStatus ? "取消成功" : "置顶成功");
        this.$set(row, "recommendStatus", Number(!recommendStatus));
      }
    },
    checkGoodsDetail(row) {
      this.currRow = row;
      this.detailVisible = true;
    },
    /** 查询基本信息列表 */
    getList() {
      this.loading = true;

      // 打印请求参数
      console.log("请求参数:", this.queryParams);

      listGoods(this.queryParams).then((response) => {
        this.goodsList = response.data;
        this.total = response.total;
        this.loading = false;
      }).catch((error) => {
        console.error("请求数据失败:", error);
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyId: null,
        createBy: null,
        createTime: null,
        createUserId: null,
        isDelete: null,
        remark: null,
        updateBy: null,
        updateTime: null,
        updateUserId: null,
        infoDetailDesc: null,
        infoFrom: 1,
        infoPicUrl: null,
        infoSimpleDesc: null,
        infoTitle: null,
        infoType: null,
        nodeId: null,
        noticeUserStatus: 0,
        openUrl: null,
        dictType: null,
        status: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isAdd = true;
      this.setStorageAdd();
      this.open = true;
      this.title = "添加基本信息";
    },
    setStorageAdd() {
      const addGoodsJson = localStorage.getItem("goods_add");
      if (!addGoodsJson) return;
      this.form = JSON.parse(addGoodsJson);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isAdd = false;
      const id = row.id || this.ids;
      getGoods(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改基本信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then((response) => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then((response) => {
              this.$message.success("新增成功");
              this.open = false;
              localStorage.removeItem("goods_add");
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除基本信息编号为"' + ids + '"的数据项？')
        .then(() => {
          return delGoods(ids);
        })
        .then(() => {
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/goods/export",
        {
          ...this.queryParams,
        },
        `goods_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
